/* Fix CSS
 * http://code.google.com/p/html5andcss3/
 * Author: kael http://weibo.com/loskael
 */
package los.kael.file;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 输出目录下文件列表到list<String>
 * 
 * @author kale
 * 
 */
public class IteaFileToList {
	private List<String> list = new ArrayList<String>();
	private String filetype = null;
	private boolean isDeepth = true;

	/**
	 * 不指定类型 指全部文件和目录
	 */
	public IteaFileToList() {
		filetype = ".+";
	}

	/**
	 * 制定文件类型
	 * 
	 * @param filetype
	 */
	public IteaFileToList(String filetype) {
		this.filetype = ".+\\." + filetype + "$";
	}

	/**
	 * 制定文件类型和包含关键字
	 * 
	 * @param include
	 * @param filetype
	 */
	public IteaFileToList(String include, String filetype) {
		if (filetype == "") {
			filetype = null;
		}
		if (include == "") {
			include = null;
		}
		if (filetype == null && include == null) {
			this.filetype = ".+";
		} else if (filetype == null) {
			this.filetype = ".*" + include + ".*";
		} else if (include == null) {
			this.filetype = ".+\\." + filetype + "$";
		} else {
			this.filetype = ".*" + include + ".*\\." + filetype + "$";
		}
	}

	/**
	 * 制定文件类型和包含关键字
	 * 
	 * @param include
	 * @param filetype
	 * @param isDeepth
	 */
	public IteaFileToList(String include, String filetype, boolean isDeepth) {
		this.isDeepth = isDeepth;
		if (filetype == "") {
			filetype = null;
		}
		if (include == "") {
			include = null;
		}
		if (filetype == null && include == null) {
			this.filetype = ".+";
		} else if (filetype == null) {
			this.filetype = ".*" + include + ".*";
		} else if (include == null) {
			this.filetype = ".+\\." + filetype + "$";
		} else {
			this.filetype = ".*" + include + ".*\\." + filetype + "$";
		}
	}

	/**
	 * 根据输入的目录(String) 递归输出到list中
	 * 
	 * @param root
	 * @return
	 * @throws Exception
	 */
	public List<String> GetAllFilesByStringToList(String root) throws Exception {
		File dir = new File(root);
		GetAllFilesByFileToList(dir);
		return list;
	}

	/**
	 * 根据输入的文件(File) 将结果递归输出到list中
	 * 
	 * @param dir
	 * @return
	 * @throws Exception
	 */
	public List<String> GetAllFilesByFileToList(File dir) throws Exception {
		File[] fs = dir.listFiles();
		String path = null;
		for (int i = 0; i < fs.length; i++) {
			path = fs[i].getAbsolutePath();
			if (path.matches(filetype) && !fs[i].isDirectory()) {
				list.add(path);
			} else if (isDeepth && fs[i].isDirectory()) {
				try {
					GetAllFilesByFileToList(fs[i]);
				} catch (Exception e) {
				}
			}
		}
		return list;
	}
}
